package com.dragon.mmochat.model.scheduleJob;

import java.util.ArrayList;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.model.enumType.MmochatNpcItemType;
import com.dragon.mmochat.model.map.MmochatMap;
import com.dragon.mmochat.model.map.MmochatPoint;
import com.dragon.mmochat.model.role.MmochatActivityNpc;
import com.dragon.mmochat.model.role.MmochatTempNpc;
import com.dragon.mmochat.service.MmochatChatService;
import com.dragon.mmochat.service.MmochatMapService;
import com.dragon.mmochat.service.MmochatNpcService;
import com.dragon.mmochat.util.MmochatUtil;

//临时活动(海盗等)
public class ActivitiesNpcJob implements Job {

	@Override
	public void execute(JobExecutionContext context) {
		try {
			MmochatActivityNpc activityNpc = (MmochatActivityNpc) context
					.getJobDetail().getJobDataMap().get("activityNpc");
			if (activityNpc != null) {
				for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
					List<Integer> mapList;
					if (activityNpc.isAppearInAllMap()) {
						mapList = activityNpc.getAppearMap();
					} else {
						mapList = new ArrayList<Integer>();
						int totalNum = activityNpc.getAppearMap().size();
						int index = MmochatUtil.getRandomValue(totalNum);
						mapList.add(activityNpc.getAppearMap().get(index));
					}
					for (int mapId : mapList) {
						for (int index = 0; index < activityNpc.getAppearNum(); index++) {
							try {
								MmochatPoint point = MmochatMapService
										.getRandReachablePoint(mapId);
								if (point != null) {
									MmochatActivityNpc npc = activityNpc
											.getClone();
									npc.setRandomFace();
									npc.setNpcId(MmochatTempNpc.getNewNpcId());
									MmochatNpcService.npcs.put(npc.getNpcId(),
											npc);
									npc.getFunctionItems().add(
											MmochatNpcItemType.击杀);
									npc.setLine(line);
									npc.setMapId(mapId);
									short x = (short) (point.getX() * 24 + Math
											.random() * 24);
									short y = (short) (point.getY() * 24 + Math
											.random() * 24);
									npc.setX(x);
									npc.setY(y);
									npc.setCreateTime(System.currentTimeMillis());
									MmochatMap theMap = MmochatMapService.maps
											.get(mapId);
									if (theMap == null) {
										continue;
									}
									theMap.addNpc(npc.getLine(), npc);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
				if (activityNpc.getSystemMsg() != null) {
					MmochatChatService
							.sendSystemMsg(activityNpc.getSystemMsg());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
